package com.wzq.proxy;

import com.wzq.annotation.WzqAutowired;
import com.wzq.utils.TransactionManager;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/** cglib代理类
 * @author wzq.Jolin
 * @company none
 * @create 2020-07-04 15:25
 */
public class CglibProxy   implements MethodInterceptor {

    private  Object  object;
    private TransactionManager transactionManager;

    public CglibProxy(Object object, TransactionManager transactionManager) {
        this.object = object;
        this.transactionManager = transactionManager;
    }

    @Override
    public Object intercept(Object proxy, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        Object result = null;
        try{
            transactionManager.beginTransaction();
            result = method.invoke(object,objects);
            transactionManager.commit();
        }catch (Exception e) {
            e.printStackTrace();
            transactionManager.rollback();
            throw e;
        }
        return result;
    }
}
